#include "gascontorolport.h"
#include "ui_gascontorolport.h"
#include "gascontroler.h"
#include "controler.h"
#include <QRandomGenerator>

gasContorolPort::gasContorolPort(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::gasContorolPort)
{
    ui->setupUi(this);
    ui->lineEdit_ip->setText(Controler::ip);

    connect(timer,&QTimer::timeout,this,[=](){
        int value = GasControler::client->readAnalogInput(Controler::gasAnalogPort);
        float changeValue = float(value)/1382.4;
        changeValue = (changeValue-Controler::zero)/Controler::gasCoefficient;
        emit gasValue(changeValue);
    });
}

gasContorolPort::~gasContorolPort()
{
    delete ui;
}

void gasContorolPort::on_pushButton_connect_clicked()
{
    if(GasControler::client->isOpen())return;

    QString ip = ui->lineEdit_ip->text();
    GasControler::client->connectTo(ip);
    if(GasControler::client->isOpen()){
        ui->pushButton_connect->setStyleSheet("background-color: rgb(166, 255, 134);"
                                              "border:2px solid #000000;");
        GasControler::client->hotStart();
        Controler::ip = ip;
        emit connectIP(ip,true);
        timer->start(30);

    }
    else {
        ui->pushButton_connect->setStyleSheet("background-color: white;"
                                              "border:2px solid #000000;");
        emit connectIP("null",false);
        timer->stop();
    }

}

void gasContorolPort::on_pushButton_disconnect_clicked()
{
    if(!GasControler::client->isOpen())return;

    GasControler::client->disConnect_();

    if(!GasControler::client->isOpen()){
        ui->pushButton_connect->setStyleSheet("background-color: white;"
                                              "border:2px solid #000000;");
        emit connectIP("null",false);
        timer->stop();
    }



}

